package com.cwises.action.login;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.core.base.BaseAction;
import com.cwises.entity.statistics.Statistics;
import com.cwises.entity.system.module.ModuleManager;
import com.cwises.entity.system.user.UserInfoManager;
import com.cwises.entity.withdraw.Withdraw;
import com.cwises.service.system.module.IModuleService;
import com.cwises.service.system.role.IRoleService;
import com.cwises.service.system.user.UserService;
import com.cwises.service.withdraw.WithdrawService;
import com.util.Global;
import com.util.Util;

@Controller
public class LoginAction extends BaseAction{
	
	@Resource(name="userService")
	private UserService userService;
	@Resource(name="roleServiceImp")
	private IRoleService roleServiceImp;
	@Resource(name="moduleServiceImp")
	private IModuleService moduleServiceImp;
	@Resource(name = "withdrawService")
	private WithdrawService withdrawService;
	
	private UserInfoManager userInfo;
    private String loginResult  = "";
    private List<ModuleManager> moduleList=null;
    private Statistics statistics;
   
	/**
     * 
    * @Title: loginPage   
    * @Description: 打开登录页面
    * @param @return    
    * @return String      
    * @author wangxinmin
    * @date 2013-12-23 上午10:59:50 
    * @throws
     */
    public String loginPage() throws Exception {
    	return "success";
    }
    /**
     * 
    * @Title: home   
    * @Description: 进入首页   
    * @param @return
    * @param @throws Exception    
    * @return String      
    * @author wangxinmin
    * @date 2014-3-11 上午11:51:59 
    * @throws
     */
    public String home() throws Exception {
    	String shopId=getShopId();
    	if(shopId==null||"".equals(shopId)){
    		return "gotoShop";
    	}else{
    		Withdraw withdraw=new Withdraw();
    		withdraw.setShop_id(shopId);
    		statistics=withdrawService.findObjectByCondition("WithdrawStatistics", withdraw);
    		if(statistics==null){
    			statistics=new Statistics();
    		}else{
    			statistics.setWt_score(statistics.getOrder_score()-statistics.getYt_score());
    			statistics.setWt_gold(statistics.getOrder_gold()-statistics.getYt_gold());
    		}
    		Map<String,Object> map=new HashMap<String,Object>();
    		SimpleDateFormat start=new SimpleDateFormat("yyyy-MM-dd 00:00:00");
    		SimpleDateFormat end=new SimpleDateFormat("yyyy-MM-dd 23:59:59");
    		Calendar calendar = Calendar.getInstance();
    		map.put("shop_id",shopId);
    		map.put("today_start",start.format(calendar.getTime()));
    		map.put("today_end",end.format(calendar.getTime()));
    		calendar.add(Calendar.DATE, -1);
    		map.put("yesterday_start",start.format(calendar.getTime()));
    		map.put("yesterday_end",end.format(calendar.getTime()));
    		calendar.add(Calendar.DATE, -6);   
    		map.put("week_start",start.format(calendar.getTime()));
    		map.put("week_end",end.format(calendar.getTime()));
    		calendar.add(Calendar.DATE, -23);
    		map.put("month_start",start.format(calendar.getTime()));
    		map.put("month_end",end.format(calendar.getTime()));
    		Statistics orderStatistics=withdrawService.findObjectByCondition("OrderStatistics", map);
    		statistics.setOrder_today(orderStatistics.getOrder_today());
    		statistics.setOrder_yesterday(orderStatistics.getOrder_yesterday());
    		statistics.setOrder_week(orderStatistics.getOrder_week());
    		statistics.setOrder_month(orderStatistics.getOrder_month());
    	}
    	return "success";
    }
    
    /**
     * 
    * @Title: logout   
    * @Description:注销    
    * @param @return
    * @param @throws Exception    
    * @return String      
    * @author wangxinmin
    * @date 2013-12-24 上午10:18:15 
    * @throws
     */
    public String logout() throws Exception {
    	HttpSession session=getHttpSession();
   		session.removeAttribute(Global.SESSION_USER); 
   		session.setMaxInactiveInterval(-1);
    	return "success";
    }
    /**
     * 
    * @Title: submitLogin   
    * @Description: 提交登录，校验  
    * @param @return
    * @param @throws Exception    
    * @return String      
    * @author wangxinmin
    * @date 2013-12-23 上午11:55:02 
    * @throws
     */
    public String submitLogin() throws Exception {
    	UserInfoManager user_r = new UserInfoManager();
    	String result = "";
    	boolean flag = true;
    	if(userInfo==null){
    		setLoginResult("必填项为空");
    		this.addActionError("必填项为空");
    		return "error";
    	}
    	String username = userInfo.getUserName();
    	String password = userInfo.getUserPwd();
//		对密码MD5加密
		String passWordMd5 = Util.MD5(password);
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("username", username);
		params.put("password", passWordMd5);
    	user_r = userService.findObjectByCondition("getUserInfoForLogin", params);
    	StringBuffer sb = new StringBuffer();
    	if (user_r == null) {
			sb.append("用户或密码错误！");
			flag = false;
		} else {
			if(user_r.getStatus()!=1){
				sb.append("用户被锁定");
				flag = false;
			}else{
				if (!passWordMd5.equals(user_r.getUserPwd())) {
					sb.append("用户或密码错误！");
					flag = false;
				}
			}
		}
    	if(flag){
    		//根据userId获取用户角色信息
//    		String userId = user_r.getUserId();
//    		List<RoleManager> roleList = new ArrayList<RoleManager>();
//    		roleList = roleServiceImp.getRoleByUserId(userId);
//    		user_r.setRoleList(roleList);
    		setCurUser(user_r,true);

    		if(password.equals(Global.USER_PSW)){
    			result = "resetpwd";
    		}else{
    			result = "success";
    		}
    	}else{
    		setLoginResult(sb.toString());
    		result = "error";
    		this.addActionError( sb.toString());
    	}
    	return result;
    }
	/**
	 * 获取当前登陆人的菜单
	 * 
	 * @Title: getAllModulesForUser
	 * @param @return
	 * @return String
	 * @author wangxinmin
	 * @date 2013-12-23 下午1:08:05
	 * @throws
	 */
	public String getAllModulesForUser() {
		UserInfoManager userInfoManager = getCurUser();
		List<ModuleManager> moduleList = moduleServiceImp.getAllModulesForUser(userInfoManager);
		setModuleList(moduleList);
		setUserInfo(userInfoManager);
		return "success";
	}
	/**
	 * @Title: 注册
	 * @author wangxinmin
	 * @throws IOException
	 */
	public void register() throws IOException {
		String flag="success";
		String tel=getParameter("tel");
		String pws=getParameter("pws");
		String code=getParameter("code");
		//验证是否为空
		if(tel==null||"".equals(tel)||pws==null||"".equals(pws)||code==null||"".equals(code)){
			flag = "nullinfo";
		}else{
			String vcode=userService.validateCode(getHttpSession(), "register", tel, code);
			if("success".equals(vcode)){
				//验证是否用户名重复
				userInfo = new UserInfoManager();
				userInfo.setUserName(tel);
				int count = (int)userService.findObjectByCondition("getUserInfoForValidate", userInfo);
				if (count > 0) {
					flag = "haveUser";
				}else{
					String passWordMd5 = Util.MD5(pws);
					String UserId=UUID.randomUUID().toString();
					userInfo.setUserId(UserId);
					userInfo.setUserPwd(passWordMd5);
					userInfo.setCreatePerson(UserId);
					userInfo.setUpdatePerson(UserId);
					userInfo.setCreateTime(new Date());
					userInfo.setUpdateTime(new Date());
					userInfo.setShopId("");
					userInfo.setStatus(1);
					try{
						userService.addUserInfoAndData(userInfo);
					}catch(Exception e){
						e.printStackTrace();
						flag="error";
					}
				}
			}else{
				flag=vcode;
			}
		}
		ServletActionContext.getResponse().getWriter().write(flag);
	}
	
	/**
	* 生成验证码,且手机必须未注册：可用与注册及修改手机号
	* 验证手机号是否已注册
	 * @throws IOException 
	*/
	@SuppressWarnings("unchecked")
    public void createRegisterCode() throws IOException{
		String flag="success";
		String tel = getParameter("tel");
		List<String> ids = userService.findByCondition("findByTelephone", tel);
		//判断手机号码是否已经存在
		if(ids.size()>0){
			//返回此手机号码已注册不可以重复注册
			flag="haveTel";
		}else {
			//生成验证码，存session，发送短信
			flag=userService.createIdentifyingCode(getHttpSession(),"register",tel);
		}
		ServletActionContext.getResponse().getWriter().write(flag);
    }
	
	 /**
     * 生成找回密码的验证码
	 * @throws IOException 
     */
    @SuppressWarnings("unchecked")
    public void createSeekPwdCode() throws IOException{
    	String result="success";
		String tel =getParameter("tel");
		List<String> ids = userService.findByCondition("findByTelephone", tel);
		//判断手机号码是否已经存在
		if(ids.size()==0){
			//返回此手机号码未注册
			result="noRegister";
		}else {
			//生成验证码，存session，发送短信
			result=userService.createIdentifyingCode(getHttpSession(),"fogetPsd",tel);
		}
		ServletActionContext.getResponse().getWriter().write(result);
    }
    
    /**
     * @Description:验证忘记密码验证码是否正确和超时
     */
    @SuppressWarnings("unchecked")
    public void validateCode() throws Exception {
    	String result="success";
    	String code = getParameter("code");
    	String telephone = getParameter("tel");
    	//验证验证码通用service
    	result=userService.validateCode(getHttpSession(),"fogetPsd",telephone,code);
		ServletActionContext.getResponse().getWriter().write(result);
    }
    
    /**
     * 找回密码
     */
    @SuppressWarnings("unchecked")
    public void seekPwd() throws Exception {
    	String result="success";
		String tel = getParameter("tel");
		String newPass = getParameter("newPass");
		List<String> ids = userService.findByCondition("findByTelephone", tel);
		//判断手机号码是否已经存在
		if(ids.size()==0){
			//返回此手机号码未注册
			result="noRegister";
		}else {
			String userId=ids.get(0);
    		try{
    			userService.updatePwd(userId,newPass);
    		}catch (Exception e) {
    			e.printStackTrace();
    			result="error";
    		}
		}
		ServletActionContext.getResponse().getWriter().write(result);
    }
    
    /**
     * 生成验证码：登录后通用
     * @throws IOException 
     */
    public void createCodeByMember() throws IOException{
    	String result="success";
		UserInfoManager user = getCurUser();
		//生成验证码，存session，发送短信
		result=userService.createIdentifyingCode(getHttpSession(),"loginCode",user.getUserName());
		ServletActionContext.getResponse().getWriter().write(result);
    }
	
	
	
    /**
	 * @return the moduleList
	 */
	public List<ModuleManager> getModuleList() {
		return moduleList;
	}

	/**
	 * @param moduleList the moduleList to set
	 */
	public void setModuleList(List<ModuleManager> moduleList) {
		this.moduleList = moduleList;
	}

	/**
	 * @return the userInfo
	 */
	public UserInfoManager getUserInfo() {
		return userInfo;
	}

	/**
	 * @param userInfo the userInfo to set
	 */
	public void setUserInfo(UserInfoManager userInfo) {
		this.userInfo = userInfo;
	}

	/**
	 * @return the loginResult
	 */
	public String getLoginResult() {
		return loginResult;
	}

	/**
	 * @param loginResult the loginResult to set
	 */
	public void setLoginResult(String loginResult) {
		this.loginResult = loginResult;
	}
	public Statistics getStatistics() {
		return statistics;
	}
	public void setStatistics(Statistics statistics) {
		this.statistics = statistics;
	}

}
